package top.peng.project.example.chapter5;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import top.peng.project.utils.Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/users")
@Slf4j
public class SpringJdbcController {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public SpringJdbcController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping(value = "")
    public List<UserEntity> queryUsers(HttpServletRequest request) {
        Utils.logInfoPrintRequestInfo(request);
        // 查询所有用户
        String sql = "select * from t_user";
        return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(UserEntity.class));
    }

    @PostMapping
    public int addUserEntity(@RequestBody UserEntity user, HttpServletRequest request) {
        Utils.logInfoPrintRequestInfo(request);

        // 添加用户
        String sql = "insert into t_user(username, password) values(?, ?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
    }

    @DeleteMapping("/{id}")
    public int delUserEntity(@PathVariable Long id, HttpServletRequest request) {
        Utils.logInfoPrintRequestInfo(request);

        // 根据主键ID删除用户信息
        String sql = "DELETE FROM t_user WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @PutMapping("/{id}")
    public int editUserEntity(@PathVariable Long id, @RequestBody UserEntity user, HttpServletRequest request) {
        Utils.logInfoPrintRequestInfo(request);

        // 根据主键ID修改用户信息
        String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id);
    }

    @GetMapping("/{id}")
    public UserEntity getUserEntity(@PathVariable Long id, HttpServletRequest request) {
        Utils.logInfoPrintRequestInfo(request);

        // 根据主键ID查询
        String sql = "select * from t_user where id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(UserEntity.class));
    }

}
